//
//  WMRecordInfoViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/9.
//

import UIKit

class WMRecordInfoViewController: WMBaseViewController {

    var record: WMRecordModel!
    
    @IBOutlet weak var orgLabel: UILabel!

    @IBOutlet weak var segBtn1: UIButton!
    @IBOutlet weak var segBtn2: UIButton!
    @IBOutlet weak var segBtn3: UIButton!
    @IBOutlet weak var segView1: UIView!
    @IBOutlet weak var segView2: UIView!
    @IBOutlet weak var segView3: UIView!
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var rightBtn: UIButton!
    @IBOutlet weak var parseH: NSLayoutConstraint!
    @IBOutlet weak var sharedBtn: UIButton!
    
    @IBOutlet weak var textBgView: UIView!
    @IBOutlet weak var contentLabel: UILabel!
    
    @IBOutlet weak var imageBgView: UIView!
    @IBOutlet weak var imageCollect: UICollectionView!
    @IBOutlet weak var imageLeftBtn: UIButton!
    @IBOutlet weak var imageRightBtn: UIButton!
    
    @IBOutlet weak var videoBgView: UIView!
    
    var player: PoAVPlayer?
    var segIndex: Int = 0
    var imgCurrentIndex: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        customNavBar.setTitle("历史记录")
        sharedBtn.isHidden = !WXApi.isWXAppInstalled()
        orgLabel.text = record.orgUrl.or("")
        imageCollect.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
        
        requestParse()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestWithDynamicList()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let player = player {
            player.pause()
        }
    }

    func requestWithDynamicList(){
        WMAgentApi.shared.requestApi(ApiEnum.myFuncList) { res in
            let data = res["data"] as? [String: Any]
            let code: String = res["code"] as! String
            if (code == "200" || code == "0"){
                let isMember = data?["memberStatus"] as? Int == 1
                UserDefaults.standard.setValue(isMember ? 1 : 0, forKey: UserDefaultsKey.isMember)
            }
        }
    }
    
    func requestParse() {
        showHUD()
        WMAgentApi.shared.requestApi(ApiEnum.parseVideo(record.orgUrl.or(""))) { res in
            Async.main { [weak self] in
                self?.hideHUD()
            }
            let dict = res["data"] as? [String: Any]
            let code: String = res["code"] as! String
            if (dict != nil), (code == "200" || code == "0") {
                let data = WMRecordModel()
                data.title = dict?["title"] as? String
                data.image = dict?["image"] as? String
                data.videoUrl = dict?["videoUrl"] as? String
                data.imgs = dict?["imgs"] as? [String]
                data.orgUrl = self.record.orgUrl
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                data.recordId = formatter.string(from: Date())
                data.imgsStr = data.imgs.or([]).joined(separator: "-[]-")
                self.record = data
                Async.main {
                    self.contentLabel.text = data.title.or("")
                    self.imgCurrentIndex = 0
                    self.imageCollect.reloadData()
                    self.videoBgView.subviews.forEach({ $0.removeFromSuperview() })
                    self.videoBgView.backgroundColor = .black
                    if let videoUrl = data.videoUrl, !videoUrl.isEmpty {
                        self.actionSegBtnClickAction(self.segBtn1)
                        if let url = URL(string: videoUrl) {
                            self.videoBgView.addSubview(self.videoPlayer)
                            PoAVPlayerCacheManager.shared.deleteAllFiles()
                            // avplayer是显示层
                            let player = PoAVPlayer(frame: self.videoBgView.bounds)
                            player.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                            // controlView是播放的交互控制层，可自定义
                            let control = PoAVPlayerControlView(player: player)
                            player.addControlLayer(control)
                            self.videoBgView.addSubview(player)
                            player.play(with: url, needCache: false)
                            self.player = player
                        }
                    }else {
                        self.player = nil
                        if let imgUrl = data.image, !imgUrl.isEmpty {
                            self.actionSegBtnClickAction(self.segBtn2)
                        }else {
                            self.actionSegBtnClickAction(self.segBtn3)
                        }
                        
                        let label = UILabel()
                        label.text = "无视频"
                        label.textColor = .white
                        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
                        self.videoBgView.addSubview(label)
                        label.snp.makeConstraints { make in
                            make.center.equalToSuperview()
                        }
                    }
                }
            }
        }
    }
    //复制原视频地址
    @IBAction func copyVideoLinkBtnClickAction(_ sender: Any) {
        UIPasteboard.general.string = record.orgUrl.or("")
        KBToast.show("复制成功")
    }
    
    @IBAction func actionSegBtnClickAction(_ sender: UIButton) {
        let segBtns: [UIButton] = [segBtn1, segBtn2, segBtn3]
        let segViews: [UIView] = [segView1, segView2, segView3]
        for i in 0..<segBtns.count {
            let btn = segBtns[i]
            let v = segViews[i]
            btn.isSelected = btn == sender
            v.isHidden = !btn.isSelected
        }
        segIndex = ["视频", "图片", "文案"].firstIndex(of: sender.titleLabel?.text).or(0)
        let views: [UIView] = [videoBgView, imageBgView, textBgView]
        for i in 0..<views.count {
            let v = views[i]
            v.isHidden = segIndex != i
        }
        if segIndex == 1 {
            imageCollect.reloadData()
        }
        if segIndex != 0, let player = player {
            player.pause()
        }
        parseH.constant = segIndex == 2 ? 360 : 410
        saveBtn.setTitle(" \(["保存视频", "保存图片", "保存文案"][segIndex])", for: .normal)
        rightBtn.setTitle(" \(["复制视频链接", "保存全部图片", "保存文案"][segIndex])", for: .normal)
        rightBtn.setImage(UIImage(named: ["remove_copy_icon", "home_save_icon", "remove_save_icon"][segIndex]), for: .normal)
    }
    //左边
    @IBAction func actionImageLeftBtnClickAction(_ sender: Any) {
        if imgCurrentIndex > 0 {
            imgCurrentIndex -= 1
            imageCollect.scrollToItem(at: IndexPath(item: imgCurrentIndex, section: 0), at: .right, animated: true)
        }
    }
    //右边
    @IBAction func actionImageRightBtnClickAction(_ sender: Any) {
        var imgUrls: [String] = []
        if let imgs = record.imgs, !imgs.isEmpty {
            imgUrls.append(contentsOf: imgs)
        }
        if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
            imgUrls.append(img)
        }
        if imgCurrentIndex < imgUrls.count - 1 {
            imgCurrentIndex += 1
            imageCollect.scrollToItem(at: IndexPath(item: imgCurrentIndex, section: 0), at: .left, animated: true)
        }
    }
    //保存文案
    @IBAction func saveBtnClickAction(_ sender: Any) {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            saveOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.saveOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
    //分享
    @IBAction func shareBtnClickAction(_ sender: Any) {
        if !WXApi.isWXAppInstalled() {
            showTips("暂无可分享的平台")
            return
        }
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            shareOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.shareOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
    //复制链接
    @IBAction func copyBtnClickAction(_ sender: Any) {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            copyOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.copyOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
    
    func saveOpt() {
        if segIndex == 0 {
            if let str = record.videoUrl, let url = URL(string: str) {
                DownloadManager.saveVideo(url: url)
            }
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let imgs = record.imgs, !imgs.isEmpty {
                imgUrls.append(contentsOf: imgs)
            }
            if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
                imgUrls.append(img)
            }
            if let url = URL(string: imgUrls[imgCurrentIndex]) {
                DownloadManager.saveImageToAlbum(url)
            }
        }else {
            UIPasteboard.general.string = contentLabel.text
            showTips("复制成功")
        }
    }
    
    func shareOpt() {
        if segIndex == 0 {
            if let url = record.videoUrl {
                let shareView = ShareView(frame: UIScreen.main.bounds)
                shareView.shareItemBlock = { index in
                    let req = SendMessageToWXReq()
                    let message = WXMediaMessage()
                    let img = WXVideoObject()
                    img.videoUrl = url
                    message.mediaObject = img
                    req.message = message
                    req.scene = Int32(index)
                    WXApi.send(req)
                }
                UIApplication.shared.delegate?.window??.addSubview(shareView)
            }
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let imgs = record.imgs, !imgs.isEmpty {
                imgUrls.append(contentsOf: imgs)
            }
            if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
                imgUrls.append(img)
            }
            if let url = URL(string: imgUrls[imgCurrentIndex]) {
                showHUD()
                let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
                    Async.main {
                        self?.hideHUD()
                    }
                    if let data = data {
                        Async.main {
                            let shareView = ShareView(frame: UIScreen.main.bounds)
                            shareView.shareItemBlock = { index in
                                let req = SendMessageToWXReq()
                                let message = WXMediaMessage()
                                let img = WXImageObject()
                                img.imageData = data
                                message.mediaObject = img
                                req.message = message
                                req.scene = Int32(index)
                                WXApi.send(req)
                            }
                            UIApplication.shared.delegate?.window??.addSubview(shareView)
                        }
                    }
                }
                task.resume()
            }
        }else {
            let shareView = ShareView(frame: UIScreen.main.bounds)
            shareView.shareItemBlock = { [weak self] index in
                let req = SendMessageToWXReq()
                req.bText = true
                req.text = self?.contentLabel.text ?? ""
                req.scene = Int32(index)
                WXApi.send(req)
            }
            UIApplication.shared.delegate?.window??.addSubview(shareView)
        }
    }
    
    func copyOpt() {
        if segIndex == 0 {
            UIPasteboard.general.string = record.videoUrl ?? ""
            showTips("复制成功")
        }else if segIndex == 1 {
            var imgUrls: [String] = []
            if let imgs = record.imgs, !imgs.isEmpty {
                imgUrls.append(contentsOf: imgs)
            }
            if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
                imgUrls.append(img)
            }
            if !imgUrls.isEmpty {
                showHUD()
            }
            for i in 0..<imgUrls.count {
                if let url = URL(string: imgUrls[i]) {
                    DownloadManager.saveImageToAlbum(url, showTips: i==imgUrls.count-1)
                }
            }
        }else {
            UIPasteboard.general.string = contentLabel.text
            showTips("复制成功")
        }
    }
    
    func requestPermission(_ complation: @escaping (Bool, String)->Void) {
        WMAgentApi.shared.requestApi(ApiEnum.permission) { res in
            let code: String = res["code"] as! String
            let message: String? = res["message"] as? String
            complation((code == "200" || code == "0"), message.or(""))
        }
        
    }
    
    lazy var videoPlayer: VideoPlayerView = {
        let player = VideoPlayerView(frame: videoBgView.bounds)
        
        return player
    }()
}

extension WMRecordInfoViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var imgUrls: [String] = []
        if let imgs = record.imgs, !imgs.isEmpty {
            imgUrls.append(contentsOf: imgs)
        }
        if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
            imgUrls.append(img)
        }
        return imgUrls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
        cell.contentView.subviews.forEach({ $0.removeFromSuperview() })

        var imgUrls: [String] = []
        if let imgs = record.imgs, !imgs.isEmpty {
            imgUrls.append(contentsOf: imgs)
        }
        if let img = record.image, !img.isEmpty, imgUrls.isEmpty {
            imgUrls.append(img)
        }
        let iv = UIImageView()
        iv.setImageUrl(imgUrls[indexPath.item])
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        cell.contentView.addSubview(iv)
        iv.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: kScreenWidth - 32, height: 295)
    }
        
}
